package com.kingdee.eas.custom.common.server;

import com.kingdee.bos.Context;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.util.app.ContextUtil;

public class AdminOrgUtils {

	public static String getOutOrgRangePersonFilter(Context ctx,
			AdminOrgUnitInfo orgUnit, boolean isInclude) throws Exception {

		UserInfo user = ContextUtil.getCurrentUserInfo(ctx);
		HROrgUnitInfo hrOrgUnit = ContextUtil.getCurrentHRUnit(ctx);
		String userID = user.getId().toString();
		String hrOrgUnitID = hrOrgUnit.getId().toString();

		StringBuffer sql = new StringBuffer();
		sql
				.append(" SELECT P.FID FROM T_BD_PERSON P LEFT JOIN T_ORG_ADMIN ORG ON P.CFDEPTID=ORG.FID");
		sql.append(" WHERE ");
		sql.append(" P.CFDEPTID IN ");
		sql.append(" ( ");

		sql
				.append(" SELECT FFROMUNITID FROM T_ORG_UNITRELATION WHERE FTOUNITID = ");
		sql.append("'").append(hrOrgUnitID).append("'");
		sql
				.append(" AND FTYPERELATIONID = '00000000-0000-0000-0000-0000000000100FE9F8B5'");
		sql.append(" AND FFromUnitID IN ");
		sql.append("(");
		sql.append(" SELECT FOrgID FROM T_PM_OrgRange ");
		sql.append(" WHERE FUserID = ");
		sql.append("'").append(userID).append("'");
		sql.append(" and FType = 20 ");
		sql.append(")");
		sql.append(")");

		if (orgUnit != null) {
			if (isInclude) {
				sql.append(" and ");
				sql.append(" ( ");
				sql.append(" org.FLongNumber = '").append(
						orgUnit.getLongNumber()).append("'");
				sql.append(" or org.FLongNumber like '").append(
						orgUnit.getLongNumber()).append("%'");
				sql.append(" ) ");
			} else {
				sql.append(" and org.FLongNumber = '").append(
						orgUnit.getLongNumber()).append("'");
			}
		}

		return sql.toString();
	}
}
